﻿using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Text;
using System.Threading.Tasks;

namespace IoTSignalR
{
    public class PipeClient
    {
        private readonly string serverName;
        private readonly string pipeName;
        private readonly PipeDirection direction;
        private readonly PipeOptions options;
        private NamedPipeClientStream namedPipeClientStream;
        public event EventHandler<string> SendMessageEvent;
        public event EventHandler<string> ReceiveMessageEvent;
        public PipeClient(string serverName, string pipeName, PipeDirection direction, PipeOptions options)
        {
            this.serverName = serverName;
            this.pipeName = pipeName;
            this.direction = direction;
            this.options = options;
        }
        public async Task StartAsync()
        {
            namedPipeClientStream = new NamedPipeClientStream(serverName, pipeName, direction, options);
            try
            {
                await namedPipeClientStream.ConnectAsync();
                SendMessageEvent += async (sender, msg) =>
                {
                    byte[] messageBytes = Encoding.UTF8.GetBytes(msg);
                    await namedPipeClientStream.WriteAsync(messageBytes, 0, messageBytes.Length);
                    await namedPipeClientStream.FlushAsync();
                };
                _ = Task.Run(async () => await ReceiveMessage());
                Console.WriteLine("客户端已启动，等待发送和接收消息...");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误: {ex.Message}");
            }
        }

        private async Task ReceiveMessage()
        {
            try
            {
                byte[] bufferBack = new byte[1024];
                while (true)
                {
                    int bytesRead = await namedPipeClientStream.ReadAsync(bufferBack, 0, bufferBack.Length);
                    if (bytesRead > 0)
                    {
                        string serverMsg = Encoding.UTF8.GetString(bufferBack, 0, bytesRead);
                        ReceiveMessageEvent.Invoke(this, serverMsg);
                    }
                    else
                    {
                        Console.WriteLine("管道已关闭，停止读取");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"客户端读取时发生异常: {ex.Message}");
            }
        }
        public void SendMsg(string msg)
        {
            SendMessageEvent.Invoke(this, msg);
        }
    }
}
